#include "groupdetaildialog.h"
#include "ui_groupdetaildialog.h"
#include "global_var.h"
#include "addgroupmemberdialog.h"
#include "utils.h"

#include <QStandardItemModel>
#include <QDebug>

GroupDetailDialog::GroupDetailDialog(Group& group, Dashboard* p, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::GroupDetailDialog)
{
    ui->setupUi(this);
    ui->lst_member->setEditTriggers(QAbstractItemView::NoEditTriggers);

    this->group = group;
    this->parent = p;

    if(current_user.getId() != this->group.getGroup_manager()) {
        ui->btn_add_member->setEnabled(false);
    }

    init();
}

GroupDetailDialog::~GroupDetailDialog()
{
    delete ui;
}

bool GroupDetailDialog::add_member(const QString &member)
{
    if(this->group.getMembers().indexOf(member) != -1) return false;

    qDebug() << get_user_by_name(member, users).getId() << endl;
    if(get_user_by_name(member, users) == "") return false;

    this->group.getMembers().push_back(member);
    get_group_by_name(this->group.getGroup_name(), current_groups).getMembers().push_back(member);
    get_group_by_name(this->group.getGroup_name(), groups).getMembers().push_back(member);

    QStandardItem* item = new QStandardItem(member);
    member_model->appendRow(item);
    update_lst_view();

    return true;
}

void GroupDetailDialog::init() {
    this->member_model = new QStandardItemModel();
    QStandardItem* item = NULL;
    QVector<QString> member = this->group.getMembers();

    ui->lbl_gname->setText(this->group.getGroup_name());
    ui->lbl_manager->setText(this->group.getGroup_manager());

    for(int i=0; i < member.size(); i++) {
        item = new QStandardItem(member[i]);
        member_model->appendRow(item);
    }

    update_lst_view();
}

void GroupDetailDialog::update_lst_view()
{
    ui->lst_member->setModel(member_model);
    ui->lst_member->show();
}

void GroupDetailDialog::on_btn_ok_clicked()
{
    parent->reload();
    this->close();
}

void GroupDetailDialog::on_btn_add_member_clicked()
{
    AddGroupMemberDialog* dialog = new AddGroupMemberDialog(this);
    dialog->show();
}
